package demo.jmeter.samples;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @date 2024/12/9 10:49
 */
public class HelloJsonArgSample extends AbstractJavaSamplerClient {
    private AtomicInteger counter = new AtomicInteger(0);
    private JSONObject template = new JSONObject();
    @Override
    public void setupTest(JavaSamplerContext context) {
        template.put("name", "HelloJsonSample");
        template.put("version", "1.0.0");
    }

    @Override
    public Arguments getDefaultParameters() {
        Arguments arguments = new Arguments();
        arguments.addArgument("url", "http://localhost:8081/post");
        arguments.addArgument("key1", "value1");
        return arguments;
    }

    @Override
    public void teardownTest(JavaSamplerContext context) {
        super.teardownTest(context);
    }

    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        int count = counter.incrementAndGet();
        template.put("count", count);
        String val = javaSamplerContext.getParameter("key1");
        template.put("key1", val);
        SampleResult sampleResult = new SampleResult();
        HttpResponse httpResponse = null;
        String body = template.toJSONString();
        String url = javaSamplerContext.getParameter("url");
        sampleResult.setSamplerData(body);
        try {
            sampleResult.sampleStart();
            httpResponse = HttpRequest.post(url).body(body).timeout(60000).execute();
            sampleResult.sampleEnd();
        } catch (Exception e) {
            e.printStackTrace();
            sampleResult.sampleEnd();
            sampleResult.setSuccessful(false);
            sampleResult.setResponseMessage(e.getMessage());
            return sampleResult;
        }
        String resBody = httpResponse.body();
        // 解析返回报文
        JSONObject resJson = JSON.parseObject(resBody);
        String code = resJson.getString("code");
        String retMsg = resJson.getString("retMsg");
        sampleResult.setResponseCode(code);
        sampleResult.setResponseMessage(retMsg);
        sampleResult.setResponseData(httpResponse.bodyBytes());
        sampleResult.setSentBytes(httpResponse.bodyBytes().length);
        if(!Objects.equals("000000", code)) {
            sampleResult.setSuccessful(false);
        } else {
            sampleResult.setSuccessful(true);
        }
        return sampleResult;
    }
}
